//
//  AppListViewController.m
//  LimitFree
//
//  Created by LZXuan on 15-6-25.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "AppListViewController.h"
#import "AppCell.h"
#import "AppModel.h"
#import "SearchViewController.h"
#import "DetailViewController.h"
#import "CategoryViewController.h"
#import "SettingsViewController.h"



@interface AppListViewController ()<UISearchBarDelegate>

@end

@implementation AppListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化
    [self navigationItemInit];
    
    [self creatTableView];

}

#pragma mark - 初始化数据
- (void)navigationItemInit {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navigationbar"] forBarMetrics:UIBarMetricsDefault];
    //导航条的内容
    [self addTitleViewWithTitle:self.title];
    
    [self addBarButtonItemWithTitle:@"分类" target:self action:@selector(leftClick:) isLeft:YES];
    [self addBarButtonItemWithTitle:@"设置" target:self action:@selector(rightClick:) isLeft:NO];
}
#pragma mark - 分类 设置
- (void)leftClick:(UIButton *)button {
    CategoryViewController *category = [[CategoryViewController alloc] init];
    
    //把分类 的类型传过去
    category.categrory = self.categoryType;
    
    //传入block-->根据 最新的categoryId 下载新数据
    __weak typeof(self)weakSelf = self;
    [category setMyBlock:^(NSString *categoryId) {
        weakSelf.currentPage = 1;
        weakSelf.categoryId = categoryId;
        //重新下载数据
        NSString *url = [NSString stringWithFormat:weakSelf.requestUrl,weakSelf.currentPage,weakSelf.categoryId];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
        //让tableView的cell 滚动到第0行
        [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    }];
    
    category.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:category animated:YES];
}
- (void)rightClick:(UIButton *)button {
    SettingsViewController *settings = [[SettingsViewController alloc] init];
    [self.navigationController pushViewController:settings animated:YES];
}
#pragma mark - 创建 tableView
- (void)creatTableView {
    //数据源数组
    self.dataArr = [[NSMutableArray alloc] init];
    //创建 tableView
    if (!self.tableView) {
        //如果没有再创建  懒加载
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64-49) style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self.view addSubview:self.tableView];
        //注册
        [self.tableView registerNib:[UINib nibWithNibName:@"AppCell" bundle:nil] forCellReuseIdentifier:@"AppCell"];
        //self.tableView.rowHeight = 100;
        
        //创建一个搜索条
        UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 44)];
        //设置代理
        searchBar.delegate = self;
        searchBar.placeholder = @"60万应用等你搜搜看哟";
        
        //放在tableView的头视图
        self.tableView.tableHeaderView = searchBar;
    }
    //取消半透明的导航条/tabBar对滚动视图的影响
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //初始化 AF
    _manager = [AFHTTPRequestOperationManager manager];
    //只下载 不解析  (二进制形式)
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}
#pragma mark - UISearcharBarDelegate
//是否可以进入编辑模式
//将要进入编辑模式调用
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //显示 cancel 按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

//将要结束编辑模式调用
//是否可以结束编辑模式
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    //隐藏cancel 按钮
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;//可以结束编辑模式
}
//点击cancel 的时候调用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";//清空内容
    //收键盘
    [searchBar resignFirstResponder];
}
//点击search 按钮 调用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    //传值
    searchVC.keyword = searchBar.text;
    //四个子类 的搜索接口不一样
    if ([self.categoryType isEqualToString:kLimitType]) {
        searchVC.searchUrl = SEARCH_LIMIT_URL;
    }else if ([self.categoryType isEqualToString:kReduceType]) {
        searchVC.searchUrl = SEARCH_REDUCE_URL;
    }else if ([self.categoryType isEqualToString:kFreeType]) {
        searchVC.searchUrl = SEARCH_FREE_URL;
    }else {
        searchVC.searchUrl = SEARCH_HOT_URL;
    }
    searchVC.hidesBottomBarWhenPushed = YES;
    //跳转
    [self.navigationController pushViewController:searchVC animated:YES];
    
}



#pragma mark - 如果不满足子类 那么可以重写
//刷新   子类调用
- (void)creatRefreshView {
    //增加下拉刷新
    
    //下面使用block 如果内部对self 进行操作 会存在 两个强引用 这样两个对象都不会释放导致内存泄露 (或者死锁就是两个对象不释放)
    //只要出现了循环引用 必须一强一弱 这样用完之后才会释放
    //arc 用 __weak  mrc __block
    
    __weak typeof (self) weakSelf = self;//弱引用
    
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //重新下载数据
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing = YES;//标记正在刷新
        weakSelf.currentPage = 1;
        
        NSString *url = nil;
        //注意 热榜接口和其他接口不一样
        if ([weakSelf.categoryType isEqualToString:kHotType]) {
            
            url = [NSString stringWithFormat:weakSelf.requestUrl,weakSelf.currentPage];
        }else {
            url = [NSString stringWithFormat:weakSelf.requestUrl,weakSelf.currentPage,weakSelf.categoryId];
        }
        
        [weakSelf addTaskWithUrl:url isRefresh:YES];
        
    }];
    
    //上拉加载更多
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //重新下载数据
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore = YES;//标记正在刷新
        weakSelf.currentPage ++;//页码加1
        
        NSString *url = nil;
        //注意 热榜接口和其他接口不一样
        if ([weakSelf.categoryType isEqualToString:kHotType]) {
            
            url = [NSString stringWithFormat:weakSelf.requestUrl,weakSelf.currentPage];
        }else {
            url = [NSString stringWithFormat:weakSelf.requestUrl,weakSelf.currentPage,weakSelf.categoryId];
        }
        
        
        [weakSelf addTaskWithUrl:url isRefresh:YES];
    }];
    
}
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.tableView footerEndRefreshing];
    }
}
//第一次下载 子类来调用
- (void)firstDownload {
    self.categoryId = @"0";
    self.currentPage = 1;
    NSString *url;
    //注意 热榜接口和其他接口不一样
    if ([self.categoryType isEqualToString:kHotType]) {
        
        url = [NSString stringWithFormat:self.requestUrl,self.currentPage];
    }else {
         url = [NSString stringWithFormat:self.requestUrl,self.currentPage,self.categoryId];
    }
    
    //增加下载任务
    [self addTaskWithUrl:url isRefresh:NO];
}

#pragma mark - 增加下载任务
- (void)addTaskWithUrl:(NSString *)url isRefresh:(BOOL)isRefresh {
    
    //__weak AppListViewController * weakSelf = self;
    // typeof(self) 获取 self 的类型
    __weak typeof(self) weakSelf = self;
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
        if (responseObject) {
            
            //如果是下拉刷新 把之前的数据清空
            if (weakSelf.currentPage == 1) {
                //清空之前的
                [weakSelf.dataArr removeAllObjects];
            }
            
            //json 数据 json 自己解析
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = dict[@"applications"];
            //遍历数组
            //数组中是字典
            for (NSDictionary *appDict in arr) {
                //放入数据模型对象
                AppModel *model = [[AppModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:appDict];
                //放入数据源数组
                [weakSelf.dataArr addObject:model];
            }
            //刷新表格
            [weakSelf.tableView  reloadData];
            
            //结束刷新
            [weakSelf endRefreshing];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

#pragma mark - tableView协议

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
//获取cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AppCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AppCell" forIndexPath:indexPath];
    //填充cell
    AppModel *model = self.dataArr[indexPath.row];
    [cell showDataWithModel:model indexPath:indexPath];
    return cell;
}

//选中cell 调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detail = [[DetailViewController alloc] init];
    AppModel *model = self.dataArr[indexPath.row];
    //传值
    detail.applicationsId = model.applicationId;
    detail.categoryType = self.categoryType;
    
    //跳转
    [self.navigationController pushViewController:detail animated:YES];
    
}





@end
